import { reactive } from "vue";
import { genFileId } from "element-plus";
import router from "@/router/index";
import { add, update, getById } from "@/api/health";
import { page as diseasePage } from "@/api/disease";
import { page as allergyPage } from "@/api/allergy";
import {
  add as addUserDisease,
  update as updateUserDisease,
  getById as diseaseGetById,
} from "@/api/userDisease";
import {
  add as addUserAllergy,
  update as updateUserAllergy,
  getById as allergyGetById,
} from "@/api/userAllergy";
import { ElMessage } from "element-plus";

export const $refs = reactive([]);

export const _$ = reactive({
  requestParam: {
    id: null,
    drug: {},
  },
  headers: {
    Authorization: `Bearer ${localStorage.getItem("ats-user-token")}`,
  },
  diseases: [],
  allergies: [],
  responseParam: {},
  rules: reactive({}),
});

export const $ = {
  init(refs) {
    if (refs) {
      $refs.length = 0;
      refs.forEach((ref) => {
        $refs.push(ref);
      });
    }
    diseasePage({
      pageNum: 0,
      pageSize: 100,
      condition: "",
    }).then((data) => {
      if (data) {
        _$.diseases.push(...data.records);
      }
    });
    allergyPage({
      pageNum: 0,
      pageSize: 100,
      condition: "",
    }).then((data) => {
      if (data) {
        _$.allergies.push(...data.records);
      }
    });
  },

  async onSubmit(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        if (router.currentRoute.value.query.id) {
          if (router.currentRoute.value.query.type == 1) {
            $.onUpdateUserDisease();
          } else {
            $.onUpdateUserAllergy();
          }
        } else {
          if (router.currentRoute.value.query.type == 1) {
            $.onAddUserDisease();
          } else {
            $.onAddUserAllergy();
          }
        }
      } else {
        console.log("校验失败！", fields);
      }
    });
  },

  onAddUserDisease() {
    addUserDisease(_$.requestParam)
      .then((_) => {
        ElMessage({
          message: "录入成功",
          type: "success",
        });
      })
      .then((_) => {
        router.push("/portal/health-data?type=1");
      });
  },

  onUpdateUserDisease() {
    updateUserDisease(_$.requestParam)
      .then((_) => {
        ElMessage({
          message: "录入成功",
          type: "success",
        });
      })
      .then((_) => {
        router.push("/portal/health-data?type=1");
      });
  },

  onAddUserAllergy() {
    addUserAllergy(_$.requestParam)
      .then((_) => {
        ElMessage({
          message: "录入成功",
          type: "success",
        });
      })
      .then((_) => {
        router.push("/portal/health-data?type=2");
      });
  },

  onUpdateUserAllergy() {
    updateUserAllergy(_$.requestParam)
      .then((_) => {
        ElMessage({
          message: "录入成功",
          type: "success",
        });
      })
      .then((_) => {
        router.push("/portal/health-data?type=2");
      });
  },

  onReset() {
    $.loadEdit();
  },

  loadEdit() {
    if (router.currentRoute.value.query.type == 1) {
      diseaseGetById(router.currentRoute.value.query.id).then((data) => {
        _$.requestParam = data;
      });
    } else {
      allergyGetById(router.currentRoute.value.query.id).then((data) => {
        _$.requestParam = data;
      });
    }
  },

  handleSizeChange(val) {
    _$.supplier.responseParam.pageSize = val;
    $.loadSuppliers();
  },

  handleCurrentChange(val) {
    _$.supplier.responseParam.pageNum = val;
    $.loadSuppliers();
  },

  handleSelectionChange(e) {
    _$.supplierSelected.length = 0;
    _$.supplierSelected.push(...e);
  },

  onExceed(files) {
    $refs[1].value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    $refs[1].value.handleStart(file);
  },

  onUploadSuccess(response) {
    _$.requestParam.healthFile = response.data;
  },

  clean() {
    _$.requestParam = {
      drug: {},
    };
    $refs.length = 0;
    _$.diseases.length = 0;
    _$.allergies.length = 0;
  },
};

export const to = {};
